import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import axiosFn from "../util/request";

export interface UserModel {
  id: number;
  name: string;
}

interface UserState {
  users: UserModel[];
}

const initialState: UserState = {
  users: [
    {
      id: 1001,
      name: "appleyk",
    },
  ],
};

const userApi = {
    queryUser:"user/query"
}

export const userQuery = createAsyncThunk(
    "user/query",
    async()=>{
        console.log('userQuery')
        return await axiosFn.onGet(userApi.queryUser);
    }
)

const userService = createSlice({
  name: "user",
  initialState,
  reducers: {
    addUser(state, action: PayloadAction<UserModel>) {
      state.users.push(action.payload);
    },
  },
  extraReducers:(builder)=>{
    builder.addCase(userQuery.fulfilled,(state,action)=>{
        state.users = action.payload
    })
  }
});

export const {addUser} = userService.actions;
export default userService.reducer;
